
// Prepare list of remortgages for relevant IDs
use "${datadir}\PSD_after_2013_03", replace // HTB_full has no remortgages
merge 1:1 psd_id using "${datadir}\HTB_main", ///
	keepusing(psd_id)	

egen psd_panel_id = group(yearbirth pcd)	

bysort psd_panel_id: egen insample = max(_merge == 3) 

keep if insample == 1
drop insample

duplicates tag psd_panel_id, gen(flag)
keep if flag > 0
drop flag

gen psd_id_ref = psd_id if _merge == 3
bysort psd_panel_id: egen max_psd_id_ref = max(psd_id_ref)

keep if advtype == 8   // remortgages
bysort psd_panel_id (date psd_id): keep if _n == 1

rename psd_id next_psd_id
rename max_psd_id_ref psd_id

rename gross_income next_income 
rename loan_val next_loan
rename date next_date

replace next_income = next_income / 1000
replace next_loan 	= next_loan / 1000

// for counterfactual analysis
rename interest next_interest
rename dealtype next_dealtype
gen next_property_val = property_val / 1000

rename mortgage_term next_mortgage_term

save "${datadir}\psd001_rmg_main", replace